<template>
  <div class="PermissionManage-container">
    <div class="PermissionManage-options">
      <el-input
        placeholder="请输入内容"
        style="width:80%;"
        @change="SearchPermissions"
        v-model="content"
      >
        <i slot="prefix" class="el-input__icon el-icon-search"></i>
      </el-input>
      <el-button type="primary" style="margin-left:20px" @click="addPermission"
        >添加权限</el-button
      >
      <el-button type="danger" @click="handleBatchDelete">批量删除</el-button>
    </div>
    <div class="PermissionManage-table" v-if="permissionList.length">
      <el-table
        :data="permissionList"
        border
        max-height="80%"
        @selection-change="handleSelectionChange"
        :default-sort="{ prop: 'date', order: 'descending' }"
        style="width: 100%"
      >
        <el-table-column type="selection" width="55"> </el-table-column>
        <el-table-column label="创建日期" sortable width="180">
          <template slot-scope="scope">
            <svg-icon icon-class="date"></svg-icon>
            <span style="margin-left: 10px">{{
              scope.row.create_time | formatDate
            }}</span>
          </template>
        </el-table-column>
        <el-table-column label="权限名" width="80">
          <template slot-scope="scope">
            <span>{{ scope.row.permission_name }}</span>
          </template>
        </el-table-column>
        <el-table-column label="描述">
          <template slot-scope="scope">
            <span>{{ scope.row.permission_description }}</span>
          </template>
        </el-table-column>
        <el-table-column label="类型" width="100">
          <template slot-scope="scope">
            <span>{{ scope.row.permission_type }}</span>
          </template>
        </el-table-column>
        <el-table-column label="路径">
          <template slot-scope="scope">
            <span>{{ scope.row.url_rule }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-button size="mini" @click="handleEdit(scope.$index, scope.row)"
              >编辑</el-button
            >

            <el-button
              size="mini"
              type="danger"
              @click="handleDelete(scope.$index, scope.row)"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        small
        :limit="limit"
        :page-size="limit"
        :current-page="page"
        @current-change="pageChange"
        layout="prev, pager, next"
        :total="count"
      >
      </el-pagination>
    </div>
    <div v-else style="display:flex;justify-content:center">
      <img
        style="width:50%;margin:0 auto"
        src="@/assets/img/search-empty.png"
      />
    </div>
    <EditDialog
      :data="EditForm"
      dialogTitle="编辑权限"
      :visible="EditDialogVisible"
      @custom-confirm="EditConfirm"
      @custom-close="EditDialogClose"
    />
    <AddDialog
      :data="addForm"
      dialogTitle="添加权限"
      :visible="AddDialogVisible"
      @custom-confirm="AddConfirm"
      @custom-close="AddDialogClose"
    />
  </div>
</template>

<script>
import { encryptData } from '@/utils/encrypt'
import EditDialog from '@/components/Dialog/EditDialog'
import AddDialog from '@/components/Dialog/AddDialog'
export default {
  components: {
    EditDialog,
    AddDialog
  },
  data() {
    return {
      limit: 5,
      page: 1,
      count: 0,
      // 权限列表
      permissionList: [],
      content: '',
      // 编辑数据
      EditDialogVisible: false,
      formLabelWidth: '80px',
      // 编辑表单
      EditForm: {},
      // 添加表单
      addForm: {
        name: '',
        description: '',
        type: '',
        url: ''
      },
      // 添加权限窗口显示标志位
      AddDialogVisible: false,
      selectedPermissions: ''
    }
  },
  mounted() {
    // 获取权限列表
    this.$nextTick(() => {
      this.getPermissionList()
    })
  },
  methods: {
    // 获取权限列表
    async getPermissionList() {
      const { limit, page } = this
      const res = await this.$API.permission.getPermissionList(limit, page)
      console.log(res)
      if (res.status == 200) {
        this.count = res.data.count
        this.permissionList = res.data.payload
      }
    },
    pageChange(page) {
      this.page = page
      this.getPermissionList()
    },
    // 添加权限确认功能回调
    async AddConfirm(formData) {
      // 整理数据
      const datas = this.$qs.stringify(formData)
      const res = await this.$API.permission.addPermission(datas)
      if (res.status == 200) {
        this.$message.success('添加成功')
        // 初始化数据
        this.AddDialogVisible = false
        this.content = ''
        this.getPermissionList()
      } else if ((res.status = 422)) {
        this.$message.warning(res.msg)
        this.AddDialogVisible = false
        this.content = ''
        this.getPermissionList()
      }
    },
    // 添加权限窗口关闭回调
    AddDialogClose() {
      this.AddDialogVisible = false
    },
    // 编辑权限
    handleEdit(id, permission) {
      console.log(permission)
      // 整理数据
      let datas = {
        id: permission.id,
        permission_name: permission.permission_name,
        permission_description: permission.permission_description,
        url_rule: permission.url_rule,
        permission_type: permission.permission_type
      }
      // 获取数据
      this.EditForm = datas
      this.EditDialogVisible = true
    },
    // 删除权限
    handleDelete(id, permission) {
      this.$confirm('此操作将永久删除该权限, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async () => {
          const res = await this.$API.permission.DeletePermission(permission.id)
          if (res.status == 200) {
            this.$message({
              type: 'success',
              message: '删除成功!'
            })
            // 初始化数据
            this.getPermissionList()
            this.content = ''
          } else {
            this.$message({
              type: 'error',
              message: '删除失败!'
            })
          }
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
    },
    // 搜索权限
    async SearchPermissions() {
      this.page = 1
      const { content, page, limit } = this
      console.log(content, page, limit)
      // 如果不存在搜索内容就获取全部
      if (!this.content) return this.getPermissionList()
      const res = await this.$API.permission.SearchPermissions(
        content,
        limit,
        page
      )
      // 如果不存在权限就显示空
      if (!res.data) this.permissionList = []
      console.log(res)
      if (res.status == 200) {
        this.permissionList = res.data.payload
        this.count = res.data.count
      }
    },
    // 关闭对话框
    EditDialogClose() {
      this.EditDialogVisible = false
    },
    // 确定编辑
    async EditConfirm(formData) {
      // 整理数据
      let { id } = formData
      const datas = {
        permission_id: id,
        ...formData
      }
      const res = await this.$API.permission.EditPermission(
        this.$qs.stringify(datas)
      )
      if (res.status == 200) {
        this.$message.success('编辑成功')
        // 初始化数据
        this.EditDialogVisible = false
        this.content = ''

        this.getPermissionList()
        this.EditForm = {}
      } else {
        this.$message.error('编辑失败')
      }
    },
    // 添加权限
    addPermission() {
      this.AddDialogVisible = true
    },
    // 获取权限
    async getPermissionsByPermissionId() {
      const { permissionPage, permissionLimit } = this
      const res = await this.$API.permission.getPermissionsByPermissionId(
        permissionPage,
        permissionLimit
      )
      if (!res.data) return (this.permissionList = [])
      if (res.status == 200) {
        this.permissionList = res.data.payload
        this.permissionCount = res.data.count
      }
    },
    // 多选项切换时
    handleSelectionChange(selection) {
      this.selectedPermissions = selection
    },
    // 批量删除
    handleBatchDelete() {
      if (this.selectedPermissions.length === 0) {
        this.$message.warning('请选择要删除的文章')
        return
      }

      this.$confirm('此操作将永久删除选中的文章, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async () => {
          const permissionIds = this.selectedPermissions.map(
            permission => permission.id
          )
          const formData = new FormData()
          formData.append('ids', permissionIds.join(','))
          const res = await this.$API.permission.BatchDeletePermission(formData)
          if (res.status === 200) {
            this.$message.success('批量删除成功')
            this.getPermissionList()
            this.content = ''
            this.selectedPermissions = []
          } else {
            this.$message.error('批量删除失败')
          }
        })
        .catch(() => {
          this.$message.info('已取消批量删除')
        })
    }
  }
}
</script>
<style scoped>
.PermissionManage-container {
  width: 100%;
  padding: 20px;
}
.PermissionManage-options {
  margin-bottom: 20px;
}
.PermissionManage-table {
  width: 100%;
  margin: 10px auto;
}
</style>